package com.project.web.wechat.controller.common;

import com.project.common.core.utils.JacksonUtil;
import com.project.common.core.utils.weChat.WeChatMiniUtil;
import com.project.common.core.utils.wx.ReqMessageUtil;
import com.project.common.core.utils.wx.message.res.BaseMessage;
import com.project.common.core.utils.wx.pojo.WeChat;
import com.project.web.wechat.service.app.WxCallBackService;
import io.swagger.annotations.Api;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 微信小程序回调
 *
 * @Author: wyy
 * @Date: 2020-04-08 13:00
 */
@Api(tags = "微信公众号服务接口")
@RestController("xyWeChatMiniNotifyController")
@RequestMapping("/weChat/anon/mini")
public class WeChatMiniNotifyController extends BaseController {
    public static final Logger log = LoggerFactory.getLogger(WeChatMiniNotifyController.class);

    @Autowired
    private WxCallBackService wxCallBackService;

    /**
     * 验证微信签名【小程序】
     *
     * @param weChat
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/weChat", method = RequestMethod.GET)
    public String validate(WeChat weChat) {
        return WeChatMiniUtil.checkSign(weChat) ? weChat.getEchostr() : "";
    }

    /**
     * 处理微信请求【小程序】
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/weChat", method = RequestMethod.POST)
    public void weChat(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter writer = null;
        try {
            //调用核心业务接受、处理消息
            Map<String, String> map = ReqMessageUtil.parseXml(request);
            log.info("\r\n *********** 微信小程序回调通知如下 *************** \r\n{}", JacksonUtil.toJsonStr(map));

            // 初始化基础消息对象
            BaseMessage baseMessage = new BaseMessage();
            baseMessage.setToUserName(map.get("ToUserName"));
            baseMessage.setFromUserName(map.get("FromUserName"));

            //消息类型
            String msgType = map.get("MsgType");
            String responseMsg = "";
            if (msgType.equals(ReqMessageUtil.MESSAGE_TYPE_TEXT)) {
                //文本消息
                log.info("\r\n ******* 小程序文本消息：{}", map.get("Content"));
                responseMsg = wxCallBackService.handleMiniTxt(map.get("Content"), map);
            } else if (msgType.equals(ReqMessageUtil.MESSAGE_TYPE_IMAGE)) {//图片消息
            } else if (msgType.equals(ReqMessageUtil.MESSAGE_TYPE_EVENT)) {//事件消息
                responseMsg = wxCallBackService.handleMiniTxt("event", map);
            }

            //响应消息
            writer = response.getWriter();
            writer.write(responseMsg);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("处理小程序回调失败:{}", ExceptionUtils.getFullStackTrace(e));
            IOUtils.closeQuietly(writer);
        }
    }
}
